<?php

/*
	info: 公共函数库
*/

if (!defined('WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

if (defined('GLOBAL_FUNC'))
{
	return;
}
define('GLOBAL_FUNC', TRUE);

//生成安全字符串
function global_Addslashes($string, $force = 0)
{
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if (!MAGIC_QUOTES_GPC || $force)
	{
		if (is_array($string))
		{
			foreach ($string as $key => $val)
			{
				$string[$key] = global_Addslashes($val, $force);
			}
		}
		else
		{
			$string = trim(addslashes($string));
		}
	}
	else
	{
		$string = global_Trim($string);
	}
	return $string;
}

//检查是否来自本站
function global_CheckCome()
{
	global $webserver;
	if ($webserver['comeurl']!='' && $webserver['webhost']!='')
	{
		if (global_FormatHost($webserver['comeurl'])==$webserver['webhost'])
		{
			return TRUE;
		}
	}
	return FALSE;
}

//检查是否字符串中含有某个字符
function global_CheckHaveVar($strall, $strone, $strcomm = ',')
{
	return strstr($strcomm.$strall.$strcomm, $strcomm.$strone.$strcomm) ? TRUE : FALSE;
}

//检查是否全不为空
function global_CheckNotEmpty($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			if (!global_CheckNotEmpty($val))
			{
				return FALSE;
			}
		}
	}
	else
	{
		if (trim($string)=='')
		{
			return FALSE;
		}
	}
	return TRUE;
}

//检查密码是否合法
function global_CheckPassword($strpass)
{
	//!preg_match('/^[0-9]{6,}$/', $strpass)
	if (strlen($strpass)>=6)
	{
		return TRUE;
	}
	return FALSE;
}

/*
 * 检查提交数据格式
 * $arySet 设定检查格式数组 array(
									0 => '表单变量名[加方括号“[]”表示数组],非数组情况下可增加“,字段名”来设置数据库字段', 
									1 => '要求类型',
									2 => '额外判断表达式[@代表变量]',
									3 => '提示错误消息[为空且非必填且有默认值就用默认值填充变量]',
									4 => '是否必填[默认0:否]',
									5 => '设定默认值[默认无，数组的默认值为单个key的默认值]'
								)
 * $isStop 是否检测到不符合条件的就停止
 * $strParam 将表单参数数组保存在webglobal的该变量下，默认保存在$webglobal['CPP']，方便用于程序后续调用
 * $strData 将表单有字段名的参数数组保存在webglobal的该变量下，默认保存在$webglobal['CPD']，用于直接写入数据库
 * $strMsg 将错误信息数组保存在webglobal的该变量下，默认保存在$webglobal['CPM']，可以通过判断该值是否为空来确定执行结果
 * return bool 是否全部校验通过
 */
function global_CheckPost($arySet, $isStop = FALSE, $strParam = 'CPP', $strData = 'CPD', $strMsg = 'CPM')
{
	global $db, $dbc, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig, $weblang;
	$tempReturn = TRUE;
	$webglobal[$strParam] = $webglobal[$strData] = $webglobal[$strMsg] = array();
	$format = array(
						/* 类型标记 => array(正则规则或者额外判断函数[@代表变量], 格式化语句[@代表变量]) */
						'int' => array('/^(-?[1-9][0-9]*|0)$/', 'intval(@)'),		//整数
						'num' => array('is_numeric(@)', 'floatval(@)'),			//数字
						'bool' => array('', 'global_ConvBool(@)'),				//取值为0或者1
						'str' => array('', 'global_ConvHtml(trim(@))'),			//去掉首尾空白和转换html的字符
						'url' => array('', 'global_ConvUrl(@)'),				//URL地址
						'email' => array('global_IsEmail(@)', ''),				//email地址
						'mobile' => array('global_IsMobile(@)', ''),			//手机
						'date' => array('global_IsDate(@)', ''),				//“年-月-日”格式
						'datetime' => array('global_IsDateTime(@)', ''),		//“年-月-日 时:分:秒”格式
						'username' => array('global_CheckUsername(@)', ''),		//用户名格式
						'password' => array('global_CheckPassword(@)', ''),		//密码格式
						'chinese' => array('/^[\x{4e00}-\x{9fa5}]+$/u', ''),	//UFT8中文格式
						'english' => array('/^[0-9A-Z_]*[A-Z]+[0-9A-Z_]*$/i', ''),	//数字字母下划线且必须有英文字符
					);
	foreach ($arySet as $tempParamSet)
	{
		//数组处理
		if (substr($tempParamSet[0], -2)=='[]')
		{
			$tempkey = substr($tempParamSet[0], 0, -2);
			//数组参数不存在
			if (!isset($webrequest[$tempkey]))
			{
				//必填
				if (isset($tempParamSet[4]) && $tempParamSet[4])
				{
					$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
					$tempReturn = FALSE;
					if ($isStop)
					{
						return $tempReturn;
					}
				}
				elseif (isset($tempParamSet[5]))
				{
					$webglobal[$strParam][$tempkey] = array($tempParamSet[5]);
				}
				continue;
			}
			else
			{
				//不是数组格式转化
				if (!is_array($webrequest[$tempkey]))
				{
					$webrequest[$tempkey] = array($webrequest[$tempkey]);
				}
				foreach ($webrequest[$tempkey] as $tempk => $tempv)
				{
					$tempk = intval($tempk);
					$tempoldv = $tempv;
					//存在校验格式检查
					if (isset($format[$tempParamSet[1]]))
					{
						//有校验规则 必填或值不为空
						if (!empty($format[$tempParamSet[1]][0]) && ((isset($tempParamSet[4]) && $tempParamSet[4]) || $tempv!=''))
						{
							//正则规则判定
							if (substr($format[$tempParamSet[1]][0], 0, 1)=='/')
							{
								$tempStatus = preg_match($format[$tempParamSet[1]][0], $tempv);
							}
							//语法判断
							else
							{
								eval('$tempStatus = ('.str_replace('@', '$tempv', $format[$tempParamSet[1]][0]).');');
							}
							if (!$tempStatus)
							{
								//非必填有默认值提示消息为空
								if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
								{
									$webglobal[$strParam][$tempkey][$tempk] = $tempParamSet[5];
								}
								//无错误消息就跳过
								elseif (!isset($tempParamSet[3]) || empty($tempParamSet[3]))
								{
								}
								else
								{
									$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
									$tempReturn = FALSE;
									if ($isStop)
									{
										return $tempReturn;
									}
								}
								continue;
							}
						}
						//有格式化函数
						if (!empty($format[$tempParamSet[1]][1]))
						{
							eval('$tempv = '.str_replace('@', '$tempv', $format[$tempParamSet[1]][1]).';');
						}
					}
					//值为空处理
					if ($tempoldv==='' || $tempv==='')
					{
						//必填报错
						if (isset($tempParamSet[4]) && $tempParamSet[4])
						{
							$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
							$tempReturn = FALSE;
							if ($isStop)
							{
								return $tempReturn;
							}
						}
						else
						{
							//值为空有默认值就赋默认值否则就用格式化的值
							$webglobal[$strParam][$tempkey][$tempk] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						}
						continue;
					}
					//额外判定条件
					if (isset($tempParamSet[2]) && !empty($tempParamSet[2]))
					{
						eval('$tempStatus = ('.str_replace('@', '$tempv', $tempParamSet[2]).');');
						if (!$tempStatus)
						{
							//非必填有默认值提示消息为空
							if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
							{
								$webglobal[$strParam][$tempkey][$tempk] = $tempParamSet[5];
							}
							//无错误消息就跳过
							elseif (!isset($tempParamSet[3]) || empty($tempParamSet[3]))
							{
							}
							else
							{
								$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
								$tempReturn = FALSE;
								if ($isStop)
								{
									return $tempReturn;
								}
							}
							continue;
						}
					}
					$webglobal[$strParam][$tempkey][$tempk] = $tempv;
				}
			}
		}
		//普通变量处理
		else
		{
			@list($tempkey, $tempdatakey) = explode(',', $tempParamSet[0]);
			//兼容获取变量名和数据库变量名一样时使用“,”即可
			if (!is_null($tempdatakey) && $tempdatakey==='')
			{
				$tempdatakey = $tempkey;
			}
			if (!isset($webrequest[$tempkey]))
			{
				//必填
				if (isset($tempParamSet[4]) && $tempParamSet[4])
				{
					$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
					$tempReturn = FALSE;
					if ($isStop)
					{
						return $tempReturn;
					}
				}
				elseif (isset($tempParamSet[5]))
				{
					$webglobal[$strParam][$tempkey] = $tempParamSet[5];
					if (!empty($tempdatakey))
					{
						$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
					}
				}
				continue;
			}
			else
			{
				$tempv = $tempoldv = $webrequest[$tempkey];
				if (isset($format[$tempParamSet[1]]))
				{
					//有校验规则 必填或值不为空
					if (!empty($format[$tempParamSet[1]][0]) && ((isset($tempParamSet[4]) && $tempParamSet[4]) || $tempv!=''))
					{
						//正则规则判定
						if (substr($format[$tempParamSet[1]][0], 0, 1)=='/')
						{
							$tempStatus = preg_match($format[$tempParamSet[1]][0], $tempv);
						}
						//语法判断
						else
						{
							eval('$tempStatus = ('.str_replace('@', '$tempv', $format[$tempParamSet[1]][0]).');');
						}
						if (!$tempStatus)
						{
							//非必填有默认值提示消息为空
							if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
							{
								$webglobal[$strParam][$tempkey] = $tempParamSet[5];
								if (!empty($tempdatakey))
								{
									$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
								}
							}
							else
							{
								$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
								$tempReturn = FALSE;
								if ($isStop)
								{
									return $tempReturn;
								}
							}
							continue;
						}
					}
					//有格式化函数
					if (!empty($format[$tempParamSet[1]][1]))
					{
						eval('$tempv = '.str_replace('@', '$tempv', $format[$tempParamSet[1]][1]).';');
					}
				}
				//值为空处理
				if ($tempoldv==='' || $tempv==='')
				{
					//必填报错
					if (isset($tempParamSet[4]) && $tempParamSet[4])
					{
						$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
						$tempReturn = FALSE;
						if ($isStop)
						{
							return $tempReturn;
						}
					}
					else
					{
						//值为空有默认值就赋默认值否则就用格式化的值
						$webglobal[$strParam][$tempkey] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						if (!empty($tempdatakey))
						{
							$webglobal[$strData][$tempdatakey] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						}
					}
					continue;
				}
				//额外判定条件
				if (isset($tempParamSet[2]) && !empty($tempParamSet[2]))
				{
					eval('$tempStatus = ('.str_replace('@', '$tempv', $tempParamSet[2]).');');
					if (!$tempStatus)
					{
						//非必填有默认值提示消息为空
						if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
						{
							$webglobal[$strParam][$tempkey] = $tempParamSet[5];
							if (!empty($tempdatakey))
							{
								$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
							}
						}
						else
						{
							$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
							$tempReturn = FALSE;
							if ($isStop)
							{
								return $tempReturn;
							}
						}
						continue;
					}
				}
				$webglobal[$strParam][$tempkey] = $tempv;
				if (!empty($tempdatakey))
				{
					$webglobal[$strData][$tempdatakey] = $tempv;
				}
			}
		}
	}
	return $tempReturn;
}

//检测字符串格式
//$inttype 检测类型 0:字母和数字 1:字母和数字且首字符为字母 2:字母 3:数字 16:十六进制
//$intmode 检测模式 0:不区分大小写 1:小写 2:大写
//$intminlen 最小长度  $intmaxlen 最大长度
function global_CheckString($string, $inttype = 0, $intmode = 0, $intminlen = 0, $intmaxlen = 0)
{
	$pattern = '/^';
	switch ($intmode)
	{
	case 1:
		$tempsign = ($inttype==16) ? 'a-f' : 'a-z';
		break;
	case 2:
		$tempsign = ($inttype==16) ? 'A-F' : 'A-Z';
		break;
	default:
		$tempsign = ($inttype==16) ? 'a-fA-F' : 'a-zA-Z';
	}
	switch ($inttype)
	{
	case 1:
		$pattern .= '['.$tempsign.']{1}['.$tempsign.'0-9]';
		break;
	case 2:
		$pattern .= '['.$tempsign.']';
		break;
	case 3:
		$pattern .= '[0-9]';
		break;
	case 4:
		$pattern .= '['.$tempsign.'0-9]';
		break;
	default:
		$pattern .= '['.$tempsign.'0-9]';
	}
	if ($intminlen<=0)
	{
		$pattern .= '*';
	}
	else
	{
		$tempminlen = ($inttype==1) ? $intminlen-1 : $intminlen;
		$pattern .= '{'.$tempminlen.',';
		if ($intmaxlen>=$intminlen)
		{
			$tempmaxlen = ($inttype==1) ? $intmaxlen-1 : $intmaxlen;
			$pattern .= $tempmaxlen;
		}
		$pattern .= '}';
	}
	$pattern .= '$/';
	if (preg_match($pattern, $string))
	{
		return TRUE;
	}
	return FALSE;
}

//检查是否点击提交按钮
function global_CheckSubmit($strvar, $allowget = 0)
{
	global $webrequest, $_SERVER;
	if (!empty($webrequest[$strvar]) && ($allowget || ($_SERVER['REQUEST_METHOD']=='POST' && global_CheckCome())))
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

//检查用户名是否合法
function global_CheckUsername($strname)
{
	if (preg_match('/^[a-z]{1}[a-z0-9]{3,14}$/', $strname))
	{
		return TRUE;
	}
	return FALSE;
}

//清除cookie
function global_ClearCookie($var, $prefix = 1)
{
	global_SetCookie($var, '', -86400*365, $prefix);
}

//清空文件夹函数
//$dir 文件夹路径  $mode 0-清空并删除当前文件夹 1-清空但不删除当前文件夹 2-清空但不删除当前及下属所有文件夹
function global_ClearDir($dir, $mode = 0)
{
	if (substr($dir, -1)=='/')
	{
		$dir = substr($dir, 0, -1);
	}
	if (is_dir($dir))
	{
		$current_dir = @opendir($dir);
		while (FALSE !== ($entryname = @readdir($current_dir)))
		{
			if ($entryname!='.' && $entryname!='..')
			{
				$fullpath = $dir.'/'.$entryname;
				if (!is_dir($fullpath))
				{
					@unlink($fullpath);
				}
				else
				{
					$undermode = ($mode==2) ? 2 : 0;
					global_ClearDir($fullpath, $undermode);
				}
			}
		}
		@closedir($current_dir);
		if ($mode==0)
		{
			@rmdir($dir);
		}
	}
}

//连接数据库
function global_ConnectDB()
{
	global $db, $webconfig;
	if (!is_object($db))
	{
		$db = new MysqlDB;
		$db->Connect($webconfig['dbhost'], $webconfig['dbuser'], $webconfig['dbpass'], $webconfig['dbname'], $webconfig['dbpconnect']);
		//unset($GLOBALS['webconfig']['dbhost'], $GLOBALS['webconfig']['dbuser'], $GLOBALS['webconfig']['dbpass'], $GLOBALS['webconfig']['dbname'], $GLOBALS['webconfig']['dbpconnect']);
	}
}

//转换0，1状态
function global_ConvBool($intnum)
{
	return (intval(trim($intnum)) > 0) ? 1 : 0;
}

//转换email地址
function global_ConvEmail($email, $tolink = 1)
{
	$email = str_replace(array('@', '.'), array('&#64;', '&#46;'), $email);
	return $tolink ? '<a href="mailto: '.$email.'">'.$email.'</a>': $email;
}

//将字符中的HTML标识转换
function global_ConvHtml($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_ConvHtml($val);
		}
	}
	else
	{
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '\'', '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), trim($string)));
	}
	return $string;
}

//IP所在地查询
function global_ConvIp($ip, $intmode = 0)
{
	global $webconfig;
	if (!preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip))
	{
		return 'IP Error';
	}

	if ($fd = @fopen(WEBFILEPATH.'/include/dat/ip.dat', 'rb'))
	{
		$ip = explode('.', $ip);
		$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];

		$DataBegin = fread($fd, 4);
		$DataEnd = fread($fd, 4);
		$ipbegin = implode('', unpack('L', $DataBegin));
		if ($ipbegin < 0) $ipbegin += pow(2, 32);
		$ipend = implode('', unpack('L', $DataEnd));
		if ($ipend < 0) $ipend += pow(2, 32);
		$ipAllNum = ($ipend - $ipbegin) / 7 + 1;

		$BeginNum = 0;
		$EndNum = $ipAllNum;

		$ip1num = $ip2num = 0;
		$ipAddr1 = $ipAddr2 = '';

		while ($ipNum>$ip2num || $ipNum<$ip1num)
		{
			$Middle= intval(($EndNum + $BeginNum) / 2);

			fseek($fd, $ipbegin + 7 * $Middle);
			$ipData1 = fread($fd, 4);
			if (strlen($ipData1) < 4)
			{
				fclose($fd);
				return 'System Error';
			}
			$ip1num = implode('', unpack('L', $ipData1));
			if ($ip1num < 0) $ip1num += pow(2, 32);

			if ($ip1num > $ipNum)
			{
				$EndNum = $Middle;
				continue;
			}

			$DataSeek = fread($fd, 3);
			if (strlen($DataSeek) < 3)
			{
				fclose($fd);
				return 'System Error';
			}
			$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
			fseek($fd, $DataSeek);
			$ipData2 = fread($fd, 4);
			if (strlen($ipData2) < 4)
			{
				fclose($fd);
				return 'System Error';
			}
			$ip2num = implode('', unpack('L', $ipData2));
			if ($ip2num < 0) $ip2num += pow(2, 32);

			if ($ip2num < $ipNum)
			{
				if ($Middle == $BeginNum)
				{
					fclose($fd);
					return 'Unknown';
				}
				$BeginNum = $Middle;
			}
		}

		$ipFlag = fread($fd, 1);
		if ($ipFlag == chr(1))
		{
			$ipSeek = fread($fd, 3);
			if (strlen($ipSeek) < 3)
			{
				fclose($fd);
				return 'System Error';
			}
			$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
			fseek($fd, $ipSeek);
			$ipFlag = fread($fd, 1);
		}

		if ($ipFlag == chr(2))
		{
			$AddrSeek = fread($fd, 3);
			if (strlen($AddrSeek) < 3)
			{
				fclose($fd);
				return 'System Error';
			}
			$ipFlag = fread($fd, 1);
			if ($ipFlag == chr(2))
			{
				$AddrSeek2 = fread($fd, 3);
				if (strlen($AddrSeek2) < 3)
				{
					fclose($fd);
					return 'System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
				fseek($fd, $AddrSeek2);
			}
			else
			{
				fseek($fd, -1, SEEK_CUR);
			}

			while (($char = fread($fd, 1)) != chr(0))
			{
				$ipAddr2 .= $char;
			}

			$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
			fseek($fd, $AddrSeek);

			while (($char = fread($fd, 1)) != chr(0))
			{
				$ipAddr1 .= $char;
			}
		}
		else
		{
			fseek($fd, -1, SEEK_CUR);
			while (($char = fread($fd, 1)) != chr(0))
			{
				$ipAddr1 .= $char;
			}

			$ipFlag = fread($fd, 1);
			if ($ipFlag == chr(2))
			{
				$AddrSeek2 = fread($fd, 3);
				if (strlen($AddrSeek2) < 3)
				{
					fclose($fd);
					return 'System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
				fseek($fd, $AddrSeek2);
			}
			else
			{
				fseek($fd, -1, SEEK_CUR);
			}
			while (($char = fread($fd, 1)) != chr(0))
			{
				$ipAddr2 .= $char;
			}
		}
		fclose($fd);

		if (preg_match('/http/i', $ipAddr2))
		{
			$ipAddr2 = '';
		}
		$ipaddr = ($intmode==1) ? $ipAddr1 : "$ipAddr1 $ipAddr2";
		$ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
		$ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
		$ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
		if (preg_match('/http/i', $ipaddr) || $ipaddr=='')
		{
			$ipaddr = 'Unknown';
		}
		//UTF-8版本进行编码转换
		if (strtolower($webconfig['webcharset']) == 'utf-8')
		{
			return iconv('gbk', 'utf-8', $ipaddr);
		}
		else
		{
			return $ipaddr;
		}
	}
	else
	{
		return 'System Error';
	}
}

//转换换行符为HTML代码
//$intp 两次换行转换为P标签 0:否 1:是
function global_ConvNewline($string, $intp = 0)
{
	$returnstr = '';
	if (trim($string)!='')
	{
		$returnstr = str_replace(array("\r\n", "\r", "\n"), '<br />', $string);
		if ($intp > 0)
		{
			$returnstr = '<p>'.$returnstr.'</p>';
			if (strpos($returnstr, '<br /><br />')!==FALSE)
			{
				$returnstr = str_replace('<br /><br />', '</p><p>', $returnstr);
				$returnstr = str_replace('<p><br />', '<p class="noindent">', $returnstr);
				$returnstr = str_replace('<p></p>', '', $returnstr);
			}
		}
	}
	return $returnstr;
}

//转换字符或数字时间为数字
function global_ConvTime($mixVar, $zone = 999)
{
	global $webserver;
	if ($zone == 999)
	{
		$zone = defined('WEBTIMEZONE') ? WEBTIMEZONE : 8;
	}
	$tempReturNnum = 0;
	if (is_array($mixVar))
	{
		$tempSetArray = explode('-', global_FormatTime($webserver['timestamp'], 'H-i-s-m-d-Y'));
		$tempSetArray = array('hour' => $tempSetArray[0], 'minute' => $tempSetArray[1], 'second' => $tempSetArray[2], 'month' => $tempSetArray[3], 'day' => $tempSetArray[4], 'year' => $tempSetArray[5]);
		$tempSetArray = array_merge($tempSetArray, $mixVar);
		$tempReturNnum = @mktime($tempSetArray['hour'], $tempSetArray['minute'], $tempSetArray['second'], $tempSetArray['month'], $tempSetArray['day'], $tempSetArray['year']);
	}
	else
	{
		$tempReturNnum = @strtotime($mixVar);
		if (!$tempReturNnum || $tempReturNnum<0)
		{
			return 0;
		}
	}
	return $tempReturNnum - $zone * 3600 + @date('Z');
}

//转换URL地址
function global_ConvUrl($strurl)
{
	$returnstr = '';
	if (trim($strurl)!='')
	{
		$returnstr = global_ConvHtml(preg_match("/^https?:\/\/.+/i", $strurl) ? $strurl : 'http://'.$strurl);
	}
	return $returnstr;
}

//递归建立文件夹
function global_CreateFolder($strfolder)
{
	if (!is_dir($strfolder))
	{
		$strfolder = preg_replace("/^".preg_quote(WEBFILEPATH, '/')."\//", "", $strfolder);
		$folderarray = explode('/', $strfolder);
		$mkfolder = WEBFILEPATH;
		foreach ($folderarray as $tempfolder)
		{
			$tempfolder = trim($tempfolder);
			if (empty($tempfolder))
			{
				continue;
			}
			$mkfolder .= '/'.$tempfolder;
			if (!is_dir($mkfolder))
			{
				if (!@mkdir($mkfolder, 0777))
				{
					return FALSE;
				}
				@touch($mkfolder.'/index.htm');
			}
		}
	}
	return TRUE;
}

//截取字符串
function global_CutStr($strVar, $intLength, $strDot = '...')
{
	global $webconfig;
	$strVarLength = strlen($strVar);
	$strDotLength = strlen($strDot);
	if ($strVarLength <= $intLength)
	{
		return $strVar;
	}

	$strVar = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;', '&nbsp;'), array('&', '"', '<', '>', ' '), $strVar);
	$strcut = '';
	//UTF-8版本特别处理
	if (strtolower($webconfig['webcharset']) == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while ($n < $strVarLength)
		{
			$t = ord($strVar[$n]);
			if ($t==9 || $t==10 || ($t>=32 && $t<=126))
			{
				$tn = 1; $n++; $noc++;
			}
			elseif ($t>=194 && $t<=223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}
			elseif ($t>=224 && $t<239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}
			elseif ($t>=240 && $t<=247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}
			elseif ($t>=248 && $t<=251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}
			elseif ($t==252 || $t==253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}
			else
			{
				$n++;
			}

			if ($noc >= $intLength-$strDotLength)
			{
				break;
			}
		}
		if ($noc > $intLength-$strDotLength)
		{
			$n -= $tn;
		}
		$strcut = substr($strVar, 0, $n);
	}
	else
	{
		for ($i=0; $i<$intLength-$strDotLength-1; $i++)
		{
			$strcut .= (ord($strVar[$i]) > 127) ? $strVar[$i].$strVar[++$i] : $strVar[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return trim($strcut.$strDot);
}

//获取debug信息
function global_DebugInfo()
{
	global $db, $webserver;
	$webserver['endmtime'] = explode(' ', microtime());
	$querynumcount = is_object($db) ? $db->querynum : 0;
	$webserver['debuginfo'] = array('time' => number_format(($webserver['endmtime'][1]+$webserver['endmtime'][0]-$webserver['beginmtime'][1]-$webserver['beginmtime'][0]), 6), 'queries' => $querynumcount);
	return TRUE;
}

//解密函数
function global_DecryptKey($txt, $authkey = '')
{
	if ($authkey == '')
	{
		$authkey = WEBAUTHKEY;
	}
	$txt = global_Key(base64_decode(str_replace(array(',', '_', '.'), array('+', '/', '='), $txt)), $authkey);
	$txtlen = strlen($txt);
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		$md5 = substr($txt, $i, 1);
		$i++;
		$tmp .= (substr($txt, $i, 1) ^ $md5);
	}
	return $tmp;
}

//加密函数
function global_EncryptKey($txt, $authkey = '')
{
	if ($authkey == '')
	{
		$authkey = WEBAUTHKEY;
	}
	srand((double)microtime()*1000000);
	$encryptkey = md5(rand(0,32000));
	$encryptkeylen = strlen($encryptkey);
	$txtlen = strlen($txt);
	$ctr = 0;
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		if ($ctr == $encryptkeylen)
		{
			$ctr = 0;
		}
		$tmp .= substr($encryptkey, $ctr, 1).(substr($txt, $i, 1) ^ substr($encryptkey, $ctr, 1));
		$ctr++;
	}
	return str_replace(array('+', '/', '='), array(',', '_', '.'), base64_encode(global_Key($tmp, $authkey)));
}

//获取文件后缀名
function global_FileExt($filename, $clearsuffix = 1)
{
	if ($clearsuffix > 0)
	{
		$filename = preg_replace("/^(.+)\.file$/i", "\\1", $filename);	//剔掉危险文件新加的后缀
	}
	$fileext = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
	if (!preg_match('/^[a-z0-9]{1,10}$/', $fileext))
	{
		$fileext = '';
	}
	return $fileext;
}

//格式化文件大小
function global_FileSize($filesize)
{
	if ($filesize >= 1073741824)
	{
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	}
	elseif ($filesize >= 1048576)
	{
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	}
	elseif ($filesize >= 1024)
	{
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	}
	else
	{
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

//格式化主机地址
function global_FormatHost($strurl)
{
	$strurl = preg_replace("/^(https?:\/\/)?(.+?)(\/.*)?$/i", "\\2", $strurl);
	return $strurl;
}

//格式化语言
function global_FormatLang($strLang)
{
	global $weblang;
	$tempLang = preg_replace("/^lang:/i", "", $strLang);
	$tempArray = explode('@@', $tempLang);
	if (!isset($weblang[$tempArray[0]]))
	{
		$tempReturn = $strLang;
	}
	elseif (!isset($tempArray[1]))
	{
		$tempReturn = $weblang[$tempArray[0]];
	}
	else
	{
		$tempArray[0] = $weblang[$tempArray[0]];
		$tempReturn = call_user_func_array('sprintf', $tempArray);
	}
	return $tempReturn;
}

//格式化时间
function global_FormatTime($timenum, $mode = 'FS', $zone = 999)
{
	global $webserver;
	if ($zone == 999)
	{
		$zone = defined('WEBTIMEZONE') ? WEBTIMEZONE : 8;
	}
	if ($timenum<=0)
	{
		$timenum = $webserver['timestamp'];
	}
	switch (strtoupper($mode))
	{
		case 'FT':	$mode = (global_FormatTime($timenum,'FD')==global_FormatTime($webserver['timestamp'],'FD')) ? 'H:i:s' : 'Y-m-d';
					break;
		case 'FS':	$mode = 'Y-m-d H:i:s';
					break;
		case 'FI':	$mode = 'Y-m-d H:i';
					break;
		case 'FD':	$mode = 'Y-m-d';
					break;
		default:	break;
	}
	return gmdate($mode, $timenum+$zone*3600);
}

//跳转地址
function global_GoToUrl($urlstr)
{
	header("Location: ".$urlstr);
	exit();
}

//高亮关键字
function global_Highlight($strall, $strshow)
{
	if (trim($strall)!='' && trim($strshow)!='')
	{
		$strshowarray = explode(' ', $strshow);
		$strshowmode = array();
		foreach ($strshowarray as $tempshow)
		{
			$tempshow = trim($tempshow);
			if ($tempshow!='')
			{
				$strshowmode[] = "/($tempshow)/i";
			}
		}
		if (count($strshowmode)>0)
		{
			$strall = preg_replace($strshowmode, "<span class=\"highlight\">\${0}</span>", $strall);
		}
	}
	return $strall;
}

//数字化变量
function global_Intval($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_Intval($val);
		}
	}
	else
	{
		$string = intval(trim($string));
	}
	return $string;
}

//检查是否合法日期
function global_IsDate($ymd, $sep = '-')
{
	if (!empty($ymd))
	{
		@list($year, $month, $day) = explode($sep, $ymd);
		return @checkdate($month, $day, $year);
	}
	else
	{
		return FALSE;
	}
}

//检查是否合法日期和时间
function global_IsDateTime($strdatetime)
{
	if (preg_match("/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/", $strdatetime, $getstr))
	{
		if (global_IsDate($getstr[1]) && global_IsTime($getstr[2]))
		{
			return TRUE;
		}
	}
	return FALSE;
}

//检查是否合法email
function global_IsEmail($email)
{
	return strlen($email)>6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//检查是否图片格式文件
function global_IsImageFile($file)
{
	return in_array(strtoupper(global_FileExt($file)),array('GIF','JPG','PNG'));
}

//检查是否手机
function global_IsMobile($mobile)
{
	return preg_match("/^1[0-9]{10}$/", $mobile);
}

//检查是否合法时间
function global_IsTime($strtime, $sep = ':')
{
	return preg_match("/^([0-1]?[0-9]|2[0-3]){$sep}([0-5]?[0-9]){$sep}([0-5]?[0-9])$/", $strtime);
}

//密码运算
function global_Key($txt, $authkey)
{
	$authkey = md5($authkey);
	$txtlen = strlen($txt);
	$authkeylen = strlen($authkey);
	$ctr = 0;
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		if ($ctr == $authkeylen)
		{
			$ctr = 0;
		}
		$tmp .= substr($txt, $i, 1) ^ substr($authkey, $ctr, 1);
		$ctr++;
	}
	return $tmp;
}

//载入语言
function global_LoadLang($filename, $isreturn = 0)
{
	global $webconfig;
	$isok = @include WEBFILEPATH.'/language/'.$webconfig['weblang'].'/'.$filename.'.lang.php';
	if ($isok)
	{
		if ($isreturn)
		{
			return $weblang;
		}
		else
		{
			$GLOBALS['weblang'] += $weblang;
		}
	}
}

//改良MD5
function global_Md5($strVar)
{
	return ($strVar != '') ? md5('a-p-p,'.md5($strVar).',f-l-y') : '';
}

//分页函数
function global_Page($intnum, $intpernum, $intcurpage, $strlinkurl, $intshowlinks = 7, $intmaxpages = 0, $strsign = '@@')
{
	$intnum = abs(intval($intnum));
	$intpernum = max(1, intval($intpernum));
	$intcurpage = max(1, intval($intcurpage));
	$intshowlinks = max(1, intval($intshowlinks));
	$intmaxpages = abs(intval($intmaxpages));
	$returnarray = array();

	if ($intnum > 0)
	{
		$allabspages = $allpages = $startpage = $endpage = 0;
		$allabspages = ceil($intnum/$intpernum);
		$allpages = ($intmaxpages>0 && $intmaxpages<$allabspages) ? $intmaxpages : $allabspages;
		$intcurpage = ($intcurpage>$allpages) ? $allpages : $intcurpage;

		$startpage = $intcurpage-floor($intshowlinks/2);
		$endpage = $intcurpage+floor($intshowlinks/2);
		if ($startpage>0 && $endpage>$allpages)
		{
			$startpage = ($endpage-$allpages<$startpage) ? $startpage-$endpage+$allpages : 1;
			$endpage = $allpages;
		}
		elseif ($startpage<=0 && $endpage<=$allpages)
		{
			$endpage = ($endpage-$startpage+1<=$allpages) ? $endpage-$startpage+1 : $allpages;
			$startpage = 1;
		}
		elseif ($startpage<=0 && $endpage>$allpages)
		{
			$startpage = 1;
			$endpage = $allpages;
		}

		$returnarray['datanum'] = $intnum;
		$returnarray['pernum'] = $intpernum;
		$returnarray['pagenum'] = $allpages;
		$returnarray['curpage'] = $intcurpage;
		$returnarray['page'] = array();

		if ($strlinkurl!='')
		{
			$returnarray['prev'] = ($intcurpage>1) ? str_replace($strsign, $intcurpage-1, $strlinkurl) : '';
			$returnarray['first'] = ($startpage>1) ? str_replace($strsign, 1, $strlinkurl) : '';
			$returnarray['front'] = ($startpage>2) ? str_replace($strsign, ceil((1+$startpage)/2), $strlinkurl) : '';
			for ($i=$startpage; $i<=$endpage; $i++)
			{
				$returnarray['page'][$i] = str_replace($strsign, $i, $strlinkurl);
			}
			$returnarray['back'] = ($endpage<$allpages-1) ? str_replace($strsign, ceil(($endpage+$allpages)/2), $strlinkurl) : '';
			$returnarray['last'] = ($endpage<$allpages) ? str_replace($strsign, $allpages, $strlinkurl) : '';
			$returnarray['next'] = ($intcurpage<$allpages) ? str_replace($strsign, $intcurpage+1, $strlinkurl) : '';
			$returnarray['input'] = ($startpage>2 || $endpage<$allpages-1) ? 'onKeyDown="javascript:if(window.event.keyCode==13 && this.value!=\'\'){window.location=\''.str_replace($strsign, '\'+this.value+\'', $strlinkurl).'\';}"' : '';
		}
		else
		{
			$returnarray['prev'] = ($intcurpage>1) ? $intcurpage-1 : 0;
			$returnarray['first'] = ($startpage>1) ? 1 : 0;
			$returnarray['front'] = ($startpage>2) ? ceil((1+$startpage)/2) : 0;
			for ($i=$startpage; $i<=$endpage; $i++)
			{
				$returnarray['page'][$i] = $i;
			}
			$returnarray['back'] = ($endpage<$allpages-1) ? ceil(($endpage+$allpages)/2) : 0;
			$returnarray['last'] = ($endpage<$allpages) ? $allpages : 0;
			$returnarray['next'] = ($intcurpage<$allpages) ? $intcurpage+1 : 0;
			$returnarray['input'] = ($startpage>2 || $endpage<$allpages-1) ? 1 : 0;
		}
	}
	
	return $returnarray;
}

//生成随机字符
function global_Random($length, $numeric = 0)
{
	PHP_VERSION<'4.2.0' and mt_srand((double)microtime() * 1000000);
	if ($numeric)
	{
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	}
	else
	{
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++)
		{
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

//检查数组中是否有某个值
//$intarray 返回数组格式 0:否 1:是
function global_SearchArray($str, $array, $key = '', $intarray = 0)
{
	$returnarray = array();
	foreach ($array as $k => $v)
	{
		if ($key=='')
		{
			if ($v==$str)
			{
				if ($intarray==0)
				{
					return $k;
				}
				else
				{
					$returnarray[] = $k;
				}
			}
		}
		else
		{
			if (isset($v[$key]) && $v[$key]==$str)
			{
				if ($intarray==0)
				{
					return $k;
				}
				else
				{
					$returnarray[] = $k;
				}
			}
		}
	}
	if ($intarray==0)
	{
		return FALSE;
	}
	else
	{
		return $returnarray;
	}
}

//设置cookie
function global_SetCookie($var, $value, $life = 0, $prefix = 1)
{
	global $webconfig, $webserver, $_SERVER;
	setcookie(($prefix ? $webconfig['cookiepre'] : '').$var, $value,
		$life ? $webserver['timestamp']+$life : 0, $webconfig['cookiepath'],
		$webconfig['cookiedomain'], $_SERVER['SERVER_PORT']==443 ? 1 : 0);
}

//显示提示信息
function global_ShowMessage($showmessage, $urlforward = '', $extra = '', $morelink = array())
{
	global $db, $dbc, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig, $weblang;

	if (is_string($showmessage) && substr($showmessage, 0, 5)=='lang:')
	{
		$showmessage = global_FormatLang($showmessage);
	}
	$webglobal['showmessage'] = $showmessage;
	$webglobal['smgurlforward'] = $urlforward;
	$webglobal['smgextra'] = $extra;
	$webglobal['morelink'] = $morelink;
	$webglobal['isautojump'] = FALSE;
	if ($webglobal['smgurlforward']!='' && $webglobal['smgextra']!='STOP')
	{
		$webglobal['isautojump'] = TRUE;
		if (!WEBDEBUG)
		{
			$webglobal['htmlhead'][] = '<meta http-equiv="refresh" content="3;url='.$webglobal['smgurlforward'].'" />';
		}
	}
	template_Display("showmessage");
	exit();
}

//去除变量前后的空格
function global_Trim($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_Trim($val);
		}
	}
	else
	{
		$string = trim($string);
	}
	return $string;
}
